package com.transaction.simulate.service.impl;

import com.transaction.simulate.mapper.IndexMapper;
import com.transaction.simulate.model.vo.FundYieldVo;
import com.transaction.simulate.service.IndexService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private IndexMapper indexMapper;

    /**
     * 查询首页信息
     * @param fundYieldVo
     * @return
     */
    @Override
    public Map<String, Object> getIndexData(FundYieldVo fundYieldVo) {

        if(Objects.isNull(fundYieldVo.getMonth())){
            fundYieldVo.setMonth("1");
        }

        Map<String,Object> retMap = new HashMap<>();
        //1、查询横坐标时间
        List<String> transDateList = indexMapper.selectFundYieldTransDate(fundYieldVo);
        //2、查询纵坐标内容
        List<FundYieldVo> fundYieldVoList = indexMapper.selectFundYieldVoList(fundYieldVo);
        //3、产品名称
        List<String> fundNameList = new ArrayList<>();

        fundYieldVoList.forEach(fundYield ->{
            List<String> fundIncomeList = Arrays.asList(fundYield.getFundIncomes().split(","));
            List<String> dateList = Arrays.asList(fundYield.getTransDates().split(","));

            Map<String,String> transIncomeMap = buildDateToFundIncome(dateList,fundIncomeList);
            List<BigDecimal> data = new ArrayList<>();
            transDateList.forEach(transDate ->{
                data.add(new BigDecimal(MapUtils.getString(transIncomeMap,transDate,"0")));
            });
            fundYield.setData(data);
            fundYield.setName(fundYield.getName() + "(" + fundYield.getFundCode() + ")");
            fundNameList.add(fundYield.getName());
        });

        if(CollectionUtils.isEmpty(fundYieldVoList)){
            retMap.put("transDateList",new ArrayList<String>());
            retMap.put("fundYieldVoList",new ArrayList<FundYieldVo>());
            retMap.put("fundNameList",new ArrayList<String>());
        }else{
            retMap.put("transDateList",transDateList);
            retMap.put("fundYieldVoList",fundYieldVoList);
            retMap.put("fundNameList",fundNameList);
        }

        return retMap;
    }

    /**
     * 组装每日的收益率
     * @param dateList
     * @param fundIncomeList
     * @return
     */
    @Override
    public Map<String, String> buildDateToFundIncome(List<String> dateList, List<String> fundIncomeList) {
        Map<String,String> transIncomeMap = new HashMap<>();
        int size = dateList.size();
        for (int i = 0;i < size;i++) {
            transIncomeMap.put(dateList.get(i),fundIncomeList.get(i));
        }
        return transIncomeMap;
    }
}
